package sort;

import java.util.Arrays;

/**
 * 冒泡排序
 * 将相邻的数依次比较，每次循环把大的数往下沉
 */
public class Bubble {   //时间复杂度：O(n^2)；适用场景：待排序个数较少

    public static void main(String[] args) {
        Integer[] arr = {4,3,5,6,1,2};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(Comparable[] a){
        for(int i=a.length-1;i>=0;i--){
            for(int j=0;j<i;j++){
                if(greater(a[j],a[j+1])){
                    exch(a,j,j+1);
                }
            }
        }
    }

    public static boolean greater(Comparable v,Comparable w){
        return v.compareTo(w)>0;  //v>=w，返回true；v<w返回false
    }

    public static void exch(Comparable[] a,int i,int j){
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
